// subPages/health/management/management.js
var util =  require('../../../utils/util.js');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    btnTxt: {
      btnTxt: '确认'
    },
    evalList: [{ tempFilePaths: [], imgList: [] }],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if(options.type){
      wx.setNavigationBarTitle({
        title: '减重管理' + '（'+ that.setTitle(options.type) +'）'  //页面标题为路由参数
      })
      that.setData({
        type: options.type,
        time: util.setTime14(new Date()),
        date: util.setTime7(new Date()),
        timeText: that.setTitle(options.type) + '时间'
      })
      if(options.date){
        that.setData({
          date: options.date
        })
      }
    }
  },

  //设置标题
  setTitle:function(type){
    let text = ''
    switch (type) {
      case '1':
        text = '早餐'
        break;
      case '2':
        text = '午餐'
        break;
      case '3':
        text = '晚餐'
        break;
      case '4':
        text = '加餐'
        break;
    }
    return text
  },

  bindTimeChange:function(e){
    this.setData({
      time: e.detail.value
    })
  },

  bindDateChange:function(e){
    this.setData({
      date: e.detail.value
    })
  },

  bindTextArea:function(e){
    this.setData({
      textArea: e.detail.value
    })
  },

  //添加图片
  joinPicture: function (e) {
    var index = e.currentTarget.dataset.index;
    var evalList = this.data.evalList;
    var that = this;
    var imgNumber = evalList[index].tempFilePaths;
    if (imgNumber.length >= 6) {
      util.showModal('提示','最多上传六张图片')
      return;
    }
    wx.showActionSheet({
      itemList: ["从相册中选择", "拍照"],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage("album", imgNumber);
          } else if (res.tapIndex == 1) {
            that.chooseWxImage("camera", imgNumber);
          }
        }
      }
    })
  },

  //选择图片
  chooseWxImage: function (type, list) {
    var img = list;
    var len = img.length;
    var that = this;
    var evalList = this.data.evalList;
    wx.chooseImage({
      count: 6,
      sizeType: ["original", "compressed"],
      sourceType: [type],
      success: function (res) {
        // console.log(res)
        var addImg = res.tempFilePaths;
        var addLen = addImg.length;
        if ((len + addLen) > 6) {
          for (var i = 0; i < (addLen - len); i++) {
            var str = {};
            str.pic = addImg[i];
            img.push(str);
          }
        } else {
          for (var j = 0; j < addLen; j++) {
            var str = {};
            str.pic = addImg[j];
            img.push(str);
          }
        }
        that.setData({
          evalList: evalList
        })
        that.upload(img);
      },
    })
  },

  //删除图片
  clearImg: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index;
    var evalList = that.data.evalList;
    wx.request({
      url: app.globalData.apiUrl +'/Api/First/delete',
      data: {
        file: evalList[0].tempFilePaths[index]
      },
      method: 'get',
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        // console.log(res)
        if(res.data == 1){
          var img = evalList[0].tempFilePaths;
          var img2 = evalList[0].imgList;
          img.splice(index, 1);
          img2.splice(index, 1);          
          that.setData({
            evalList: evalList
          })
        }
      },
      fail: function (res) {
        console.log("失败",res);
      }
    })
  },

  //多张图片上传
  upload: function (path) {
    var that = this;
    var curImgList = [];
    for (var i = 0; i < path.length; i++) {
      wx.showToast({
        icon: "loading",
        title: "正在上传"
      }),
      wx.uploadFile({
        url: app.globalData.apiUrl + '/upload',//接口处理在下面有写
        filePath: path[i].pic,
        name: 'img',
        header: { "Content-Type": "multipart/form-data" },
        formData: {
          douploadpic: '1'
        },
        success: function (res) {
          // console.log(res)
          curImgList.push(res.data);
          var evalList = that.data.evalList;
          evalList[0].imgList = curImgList;
          that.setData({
            evalList: evalList
          })
        },
        fail: function (e) {
          util.showModal('提示','上传失败')
          return
        },
        complete: function () {
          wx.hideToast();  //隐藏Toast
        }
      })
    }
  },

  setImg:function(){
    var that = this 
    var imgList = that.data.evalList[0].imgList
    var imgPort = "";//图片地址，多张以逗号分割
    for (var j = 0; j < imgList.length; j++) {
      imgPort = imgList[j] + "," + imgPort;
    }
    imgPort = imgPort.substring(0,imgPort.length-1);
    // console.log(imgPort)
    return imgPort
  },

  //保存信息
  lickBtn:function(){
    var that = this
    if(!that.data.evalList){
      util.showModal('提示','请选择上传的照片')
      return
    }
    var img =  that.setImg()
    if(!img){
      util.showModal('提示','请选择上传的照片')
      return
    }
    var textArea = that.data.textArea?that.data.textArea: ''
    console.log(that.data.time)
    if(that.data.type == '4'){
      wx.request({
        url: app.globalData.apiUrl +'/user_add_eat', //接口地址
        data: {
          userid: app.globalData.userId,
          type: that.data.type,
          remark: textArea,
          img: img,
          eattime: that.data.time,
          createtime: Date.parse(new Date(that.data.date.replace(/-/g, '/')))/1000,
          date: that.data.date
        },
        method: 'post',
        header: {
            'content-type': 'application/x-www-form-urlencoded' //默认值
        },
        success: function (res) {
          console.log(res)
          if(res.data.code == '200'){
            //返回
            var pages = getCurrentPages();
            if(pages.length > 1){
              var prePage = pages[pages.length - 2];
              prePage.changeData(that.data.date)
            }
            //返回
            wx.navigateBack({
              delta:1
            })
          }else{
            util.showModal('提示','记录失败')
            return;
          }
        }
      })
    }else{
      wx.request({
        url: app.globalData.apiUrl +'/user_add_eat', //接口地址
        data: {
          userid: app.globalData.userId,
          type: that.data.type,
          remark: textArea,
          img: img,
          createtime: Date.parse(new Date(that.data.date.replace(/-/g, '/')))/1000,
          date: that.data.date
        },
        method: 'post',
        header: {
            'content-type': 'application/x-www-form-urlencoded' //默认值
        },
        success: function (res) {
          // console.log(res)
          if(res.data.code == '200'){
            //返回
            var pages = getCurrentPages();
            if(pages.length > 2){
              var prePage = pages[pages.length - 2];
              prePage.changeData(that.data.date)
            }
            //返回
            wx.navigateBack({
              delta:1
            })
          }else{
            util.showModal('提示','记录失败')
            return;
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: 'PAPN健康管理',
      path: 'pages/index/index',
      success: function(res) {
        // res.shareTickets 
      },
      fail: function(res) {
          console.log(res)
      }
    }
  }
})
